<script>
import store from '@/store'
import StoreModel from '@/common/model/Store'
import { getSceneData } from './core/app'
import { isObject } from './utils/util'
// #ifdef APP-PLUS
import { audioPlayer } from './utils/audioPlayer'
import * as PickApi from '@/api/order/pick'
import * as OrderApi from '@/api/order/order'
import PickerStatusEnum from "@/common/enum/setting/pickerStatus"
import PickerModeEnum from "@/common/enum/setting/pickMode"
// #endif

export default {

  /**
   * 全局变量
   */
  globalData: {
    // im消息socket实例
    imWSInstance: null
  },

  /**
   * 初始化完成时触发
   */
  onLaunch({ path, query, scene }) {
    // #ifdef MP
    // 小程序主动更新
    this.updateManager()
    this.getSetting()
    // #endif
    // app启动参数
    this.onStartupQuery(isObject(query) ? query : {})

    // 定时查询未处理拣货单并进行语音播报
    this.onPickTiming()
    this.initPush()
	console.log("1111111")
  },
  methods: {

    // app启动参数
    onStartupQuery(query) {
      // 获取二维码场景值
      // const scene = getSceneData(query)
    },

    // 获取基础信息
    getStoreInfo() {
      StoreModel.data(false)
    },

    // 小程序主动更新
    updateManager() {
      const updateManager = uni.getUpdateManager()
      updateManager.onCheckForUpdate(res => {
        // 请求完新版本信息的回调
        // console.log(res.hasUpdate)
      })
      updateManager.onUpdateReady(() => {
        uni.showModal({
          title: '更新提示',
          content: '新版本已经准备好，即将重启应用',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })
      updateManager.onUpdateFailed(() => {
        // 新的版本下载失败
        uni.showModal({
          title: '更新提示',
          content: '新版本下载失败',
          showCancel: false
        })
      })
    },

    // 小程序配置信息
    getSetting() {
      const systemInfo = uni.getSystemInfoSync()
      let system = {
        statusBarHeight: systemInfo.statusBarHeight,
        navHeight: systemInfo.platform === 'ios' ? 44 : 48,
        needAddBottom: /iphone x|11|12|13/i.test(systemInfo.model),
        model: systemInfo.model
      }
      // #ifdef MP
      const accountInfo = uni.getAccountInfoSync();
      const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
      const navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight
      system = {
        ...system,
        navBarHeight,
        menuRight: systemInfo.screenWidth - menuButtonInfo.right,
        menuBottom: navBarHeight - menuButtonInfo.bottom,
        menuLeft: menuButtonInfo.left,
        menuHeight: menuButtonInfo.height,
        env: accountInfo.miniProgram.envVersion
      }
      // #endif
      store.commit('SET_SYSTEM', system)
    },

    // 定时查询未处理拣货单并进行语音播报
    onPickTiming() {
      // #ifdef APP-ANDROID
      const keepAlive = uni.requireNativePlugin('Ba-KeepAliveSuit')
      keepAlive.onKeep({ title: "门店履约", content: "正在进行门店履约。" }, (res) => {
        setInterval(function () {
          if (!store.getters.token || !store.getters.store) {
            return
          }
          const pickMode = store.getters.pickConfig.pickMode
          const pickerStatus = store.getters.pickerStatus
          PickApi.getTabPop('').then(result => {
            console.log('result', JSON.stringify(result))
            const { data } = result
            if (!data) return
            if (data.turnCount > 0 && pickerStatus === PickerStatusEnum.NO.value &&
              pickMode === PickerModeEnum.SEND.value) {
              // 待转派
              audioPlayer.addAudio('/static/mp3/audio_pick_turn_ds.mp3');
            }
            if (data.unappropriatedCount > 0 &&
              pickMode === PickerModeEnum.ROB.value) {
              // 待抢单
              audioPlayer.addAudio('/static/mp3/audio_pick_rob_ds.mp3');
            }
            if (data.pendingCount > 0 && pickerStatus !== PickerStatusEnum.NO.value) {
              // 待拣货
              audioPlayer.addAudio('/static/mp3/audio_pick_new_ds.mp3');
            }
            if (data.turnCount > 0 && pickerStatus === PickerStatusEnum.NO.value &&
              store.getters.pickConfig.isReview === 1) {
              // 待复核
              audioPlayer.addAudio('/static/mp3/audio_pick_review_ds.mp3');
            }
          }).catch(() => { })
          if (pickerStatus == PickerStatusEnum.NO.value) {
            OrderApi.getTabPop('').then(result => {
              const { data } = result
              if (!data) return
              if (data.newOrderCount > 0 || data.waitPrepareCount > 0 || data.abnormalCount > 0) {
                // 需要处理的订单
                audioPlayer.addAudio('/static/mp3/audio_pending_new_order.mp3');
              }
            })
          }
        }, 1000 * 60);
      });
      // #endif

      // #ifdef APP-IOS
      // 定时检查本地拣货单-暂时给IOS使用
      setInterval(function () {
        if (!store.getters.token || !store.getters.store) {
          return
        }
        const pickMode = store.getters.pickConfig.pickMode
        const pickerStatus = store.getters.pickerStatus
        PickApi.getTabPop('').then(result => {
          console.log('result', JSON.stringify(result))
          const { data } = result
          if (!data) return
          if (data.turnCount > 0 && pickerStatus === PickerStatusEnum.NO.value &&
            pickMode === PickerModeEnum.SEND.value) {
            // 待转派
            audioPlayer.addAudio('/static/mp3/audio_pick_turn_ds.mp3');
          }
          if (data.unappropriatedCount > 0 &&
            pickMode === PickerModeEnum.ROB.value) {
            // 待抢单
            audioPlayer.addAudio('/static/mp3/audio_pick_rob_ds.mp3');
          }
          if (data.pendingCount > 0 && pickerStatus !== PickerStatusEnum.NO.value) {
            // 待拣货
            audioPlayer.addAudio('/static/mp3/audio_pick_new_ds.mp3');
          }
          if (data.turnCount > 0 && pickerStatus === PickerStatusEnum.NO.value &&
            store.getters.pickConfig.isReview === 1) {
            // 待复核
            audioPlayer.addAudio('/static/mp3/audio_pick_review_ds.mp3');
          }
        }).catch(() => { })
        if (pickerStatus == PickerStatusEnum.NO.value) {
          OrderApi.getTabPop('').then(result => {
            const { data } = result
            if (!data) return
            if (data.newOrderCount > 0 || data.waitPrepareCount > 0 || data.abnormalCount > 0) {
              // 需要处理的订单
              audioPlayer.addAudio('/static/mp3/audio_pending_new_order.mp3');
            }
          })
        }
      }, 1000 * 60);
      // #endif
    },

    // 监听push推送
    initPush() {
      console.log('initPush')

      uni.getPushClientId({
        success(res) {
          console.log('推送标识：', res.cid);
        },
        fail(err) {
          console.log(err)
        }
      })
      // 监听推送消息
      uni.onPushMessage((message) => {
        console.log('收到推送：', message);

      //   uni.createPushMessage({
      //         title: message.title || "新消息",
      //         content: message.content || "您有一条未读消息",
      //         payload: message.data // 点击通知后传递的数据
      //       });
      // });
    },
    handleForegroundMessage(message) {
      // 前台消息可以选择是否创建通知
      if (this.shouldShowNotification(message)) {
        NotificationHelper.createNotification(message);
      }
    },

    handleBackgroundMessage(message) {
      // 后台消息直接创建通知
      NotificationHelper.createNotification(message);
    },

    shouldShowNotification(message) {
      // 根据消息类型判断是否需要显示通知
      const payload = message.payload;
      if (typeof payload === 'string') {
        try {
          const data = JSON.parse(payload);
          return data.showNotification !== false;
        } catch (e) {
          return true;
        }
      }
      return true;
    }
  }
}
</script>

<style lang="scss">
/* uView库样式 */
@import "./uni_modules/vk-uview-ui/index.scss";
/* 项目基础样式 */
@import "./app.scss";
/* iconfont图标库 */
@import "./utils/iconfont.scss";
</style>
